<template>
  <div class="chat-interface">
    <div v-if="!selectedCharacter" class="no-AICharacter">
      <el-empty description="请先选择一个角色开始聊天"></el-empty>
    </div>

    <div v-else class="chat-container">
      <!-- 角色信息头部 -->
      <div class="AICharacter-header">
        <img v-if="selectedCharacter.imageUrl" :src="selectedCharacter.imageUrl" :alt="selectedCharacter.name"
             class="AICharacter-avatar">
        <div class="AICharacter-details">
          <h2>{{ selectedCharacter?.name || '未知角色' }}</h2>
          <p>{{ selectedCharacter?.description || '暂无角色描述' }}</p>
        </div>
      </div>

      <!-- 聊天消息区域 -->
      <div class="chat-messages" ref="chatMessages">
        <div v-for="message in messages" :key="message.id" :class="['message', message.role]">
          <div class="message-content">
            <div class="message-role">{{ message.role === 'user' ? '我' : selectedCharacter?.name || '角色' }}</div>
            <p class="message-text">{{ message.content }}</p>
          </div>
        </div>
        <div v-if="isThinking" class="message thinking">
          <div class="message-content">
            <div class="message-role">{{ selectedCharacter?.name || '角色' }}</div>
            <div class="typing-indicator">
              <span></span><span></span><span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入和控制区域 -->
      <div class="chat-input-container">
        <el-input
            v-model="inputMessage"
            placeholder="输入消息..."
            class="text-input"
            @keyup.enter="sendMessage"
        />
        <div class="chat-controls">
          <el-button
              type="primary"
              icon="Message"
              @click="sendMessage"
              :disabled="!inputMessage.trim() || isThinking"
          >
            发送
          </el-button>
          <el-button
              @click="toggleVoiceInput"
              :disabled="isVoiceInputActive || isThinking"
              :class="['voice-button', isVoiceInputActive ? 'active' : '']"
              title="语音输入"
          >
            <el-icon>
              <Microphone v-if="!isVoiceInputActive"/>
              <Close v-else/>
            </el-icon>
          </el-button>
          <el-button
              @click="toggleVoiceOutput"
              :disabled="isThinking"
              :class="['voice-output-button', voiceOutputEnabled ? 'active' : '']"
              title="语音输出"
          >
            <el-icon>
              <Headset :class="voiceOutputEnabled ? 'enabled' : 'disabled'"/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, watch, nextTick} from 'vue';
import api from '../api.js';
import {Microphone, Close, Headset} from '@element-plus/icons-vue';

const props = defineProps({
  selectedCharacter: {
    type: Object,
    default: () => ({})
  }
});

const messages = ref([]);
const inputMessage = ref('');
const isThinking = ref(false);
const isVoiceInputActive = ref(false);
const voiceOutputEnabled = ref(true);
const chatMessages = ref(null);

// 语音识别相关
let recognition = null;

// 初始化语音识别
const initVoiceRecognition = () => {
  if ('webkitSpeechRecognition' in window) {
    recognition = new window.webkitSpeechRecognition();
    recognition.continuous = false;
    recognition.interimResults = false;
    recognition.lang = 'zh-CN';

    recognition.onresult = (event) => {
      const transcript = event.results[0][0].transcript;
      inputMessage.value = transcript;
    };

    recognition.onend = () => {
      isVoiceInputActive.value = false;
    };

    recognition.onerror = (event) => {
      console.error('语音识别错误:', event.error);
      isVoiceInputActive.value = false;
    };
  } else {
    console.warn('您的浏览器不支持语音识别功能');
  }
};

// 语音合成
const speakText = (text) => {
  if (!voiceOutputEnabled.value || !('speechSynthesis' in window)) {
    return;
  }

  const utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = 'zh-CN';

  // 设置语音参数
  const voices = window.speechSynthesis.getVoices();
  const chineseVoice = voices.find(voice =>
      voice.lang.includes('zh-CN') || voice.lang.includes('zh-Hans')
  );

  if (chineseVoice) {
    utterance.voice = chineseVoice;
  }

  window.speechSynthesis.speak(utterance);
};

// 切换语音输入
const toggleVoiceInput = () => {
  if (!recognition) {
    initVoiceRecognition();
  }

  if (isVoiceInputActive.value) {
    recognition.stop();
  } else {
    isVoiceInputActive.value = true;
    recognition.start();
  }
};

// 切换语音输出
const toggleVoiceOutput = () => {
  voiceOutputEnabled.value = !voiceOutputEnabled.value;
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isThinking.value) {
    return;
  }

  const userMessage = {
    id: Date.now(),
    role: 'user',
    content: inputMessage.value
  };

  messages.value.push(userMessage);
  scrollToBottom();

  inputMessage.value = '';
  isThinking.value = true;

  try {
    // 这里应该是实际调用LLM API
    // const response = await axios.post('/api/chat', {
    //   characterId: props.selectedCharacter.id,
    //   messages: messages.value
    // });

    // 调用后端API获取LLM响应
    await getLLMResponse(userMessage.content);
  } catch (error) {
    console.error('发送消息失败:', error);
    messages.value.push({
      id: Date.now() + 1,
      role: 'AICharacter',
      content: '抱歉，我暂时无法回复您的消息，请稍后再试。'
    });
  } finally {
    isThinking.value = false;
    scrollToBottom();
  }
};
let eventSource = null;
// 调用后端API获取LLM响应（处理SSE数据）
const getLLMResponse = async (userMessage) => {
  if (!props.selectedCharacter) {
    const botMessage = {
      id: Date.now() + 1,
      role: 'AICharacter',
      content: '请先选择一个角色开始对话。'
    };
    messages.value.push(botMessage);
    speakText(botMessage.content);
    return;
  }

  try {
    // 添加机器人回复到消息列表（打字状态）
    const botMessage = {
      id: Date.now() + 1,
      role: 'AICharacter',
      content: '',
      isTyping: true
    };
    // messages.value.push(botMessage);
    scrollToBottom();
    console.log('Making SSE request to:', `/test/halipote?question=${encodeURIComponent(userMessage)}`);
    // const url = `/test/halipote?question=${encodeURIComponent(userMessage)}`;
    const request = {
      conversationId: props.selectedCharacter.id*100,
      character_id: props.selectedCharacter.id,
      question: userMessage
    }
    const url = `/api/chat/character/1000?${new URLSearchParams(request)}`
    eventSource = new EventSource(url);
    // ${props.selectedCharacter.id}
    eventSource.onopen = function () {
      console.log('EventSource连接已建立');
    };

    eventSource.onmessage = function (event) {
      if (event.data === '[DONE]') {
        eventSource.close();
        return;
      }
      botMessage.content += event.data;
      console.log("EVENT: ", event.data)
      scrollToBottom();
    };

    eventSource.onerror = function () {
      console.log("error|close")
      messages.value.push(botMessage)
      speakText(botMessage.content);
      eventSource.close();
    };
    // // 使用fetch API来处理SSE流
    // const response = await fetch(`/test/halipote?question=${encodeURIComponent(userMessage)}`, {
    //   method: 'GET',
    //   headers: {
    //     'Accept': 'text/event-stream'
    //   }
    // });
    //
    // console.log('SSE response status:', response.status);
    // console.log('SSE response headers:', response.headers);

    // if (!response.ok) {
    //   throw new Error(`HTTP error! Status: ${response.status}`);
    // }

    // 检查是否有响应体
    // if (!response.body) {
    //   console.warn('No response body, using mock data');
    //   // 使用模拟数据作为备用
    //   botMessage.content = '您好！看来我们的连接有点问题，但我仍然可以与您交流。有什么我可以帮助您的吗？';
    //   botMessage.isTyping = false;
    //   scrollToBottom();
    //
    //   if (voiceOutputEnabled.value) {
    //     speakText(botMessage.content);
    //   }
    //   return;
    // }

    // const reader = response.body.getReader();
    // const decoder = new TextDecoder();
    // let fullResponse = '';

    // 添加超时处理
    // let timeoutId;
    // const timeoutPromise = new Promise((_, reject) => {
    //   timeoutId = setTimeout(() => {
    //     reject(new Error('SSE connection timeout'));
    //   }, 30000); // 30秒超时
    // });

    // 逐块处理SSE数据
    // let receivedData = false;
    // try {
    //   while (true) {
    //     const readPromise = reader.read();
    //     // 使用Promise.race来同时处理读取和超时
    //     const {done, value} = await Promise.race([readPromise, timeoutPromise]);
    //
    //     if (done) {
    //       break;
    //     }
    //
    //     receivedData = true;
    //
    //     // 解码接收到的数据
    //     const chunk = decoder.decode(value, {stream: true});
    //
    //     // 添加调试日志，查看原始数据
    //     console.log('Received SSE chunk:', chunk);
    //
    //     // 处理SSE格式的数据 - 解析data:前缀的消息
    //     // 尝试多种可能的格式
    //     let extractedText = '';
    //
    //     // 格式1: data: message
    //     const dataMatch = chunk.match(/data:\s*(.+?)(?=\ndata:|\n\n|$)/gs);
    //     if (dataMatch) {
    //       dataMatch.forEach(match => {
    //         const content = match.replace(/^data:\s*/i, '').trim();
    //         extractedText += content;
    //       });
    //     }
    //
    //     // 格式2: 尝试直接获取文本内容作为备用
    //     if (!extractedText && chunk.trim()) {
    //       console.log('No standard SSE format detected, using raw data');
    //       extractedText = chunk;
    //     }
    //
    //     // 更新消息内容
    //     if (extractedText) {
    //       botMessage.content += extractedText;
    //       fullResponse += extractedText;
    //
    //       // 滚动到底部
    //       scrollToBottom();
    //     }
    //   }
    // } finally {
    //   // 清除超时定时器
    //   clearTimeout(timeoutId);
    //
    //   // 如果没有接收到任何数据，使用模拟响应
    //   if (!receivedData) {
    //     console.warn('No data received from SSE, using mock response');
    //     botMessage.content = '嗨！看来我们的连接有点不稳定。不过没关系，我可以继续和您聊天。有什么想聊的话题吗？';
    //   }
    // }

    botMessage.isTyping = false;

    // 滚动到底部
    scrollToBottom();

    // 如果启用了语音播报，就播报回复
    if (voiceOutputEnabled.value && botMessage.content) {
      speakText(botMessage.content);
    }
  } catch (error) {
    console.error('获取LLM响应失败:', error);
    const errorMessage = {
      id: Date.now() + 1,
      role: 'AICharacter',
      content: '抱歉，目前无法连接到AI服务。请稍后再试。\n(错误: ' + error.message + ')'
    };
    // 检查是否已经添加了错误消息
    const existingError = messages.value.find(msg => msg.role === 'AICharacter' && msg.content.includes('无法连接'));
    if (!existingError) {
      messages.value.push(errorMessage);
      speakText(errorMessage.content);
      scrollToBottom();
    }
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessages.value) {
      chatMessages.value.scrollTop = chatMessages.value.scrollHeight;
    }
  });
};

// 监听角色变化，清空消息
watch(() => props.selectedCharacter, (newCharacter) => {
  if (newCharacter) {
    messages.value = [];
  }
});
</script>

<style scoped>
.chat-interface {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.no-AICharacter {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.AICharacter-header {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.AICharacter-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-right: 20px;
  object-fit: cover;
}

.AICharacter-details h2 {
  margin: 0 0 10px 0;
  color: #333;
}

.AICharacter-details p {
  margin: 0;
  color: #666;
  font-size: 14px;
  max-width: 600px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fafafa;
}

.message {
  margin-bottom: 20px;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.AICharacter,
.message.thinking {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message.user .message-content {
  background-color: #409eff;
  color: #fff;
}

.message-role {
  font-weight: bold;
  margin-bottom: 5px;
  font-size: 14px;
}

.message-text {
  margin: 0;
  line-height: 1.5;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 10px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #666;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-5px);
  }
}

.chat-input-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
  background-color: #fff;
}

.text-input {
  margin-bottom: 15px;
}

.chat-controls {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.voice-button,
.voice-output-button {
  min-width: 40px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.voice-button.active {
  background-color: #f56c6c;
  color: #fff;
}

.voice-output-button.active .Headset.enabled {
  color: #67c23a;
}

.voice-output-button .Headset.disabled {
  color: #999;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>